<template>
  <view class="container">
    <!-- 顶部logo和欢迎信息 -->
    <view class="header">
      <view class="logo">
        <!-- 医疗健康图标 - 用户将提供SVG/PNG图标替换这里 -->
        <view class="medical-icon">
          <!-- 临时使用心电图图标，用户可以替换为自己的医疗图标 -->
          <image
            src="/static/icons/medical-heart.svg"
            class="icon-image"
            mode="aspectFit"
            @error="handleIconError"
          />
        </view>
      </view>
      <view class="title">医疗健康小程序</view>
      <view class="description"
        >专业医疗健康服务，为您提供贴心的健康<br />管理</view
      >
    </view>

    <!-- 微信登录区域 -->
    <view class="wechat-login">
      <button class="wechat-btn" :disabled="loading" @click="handleWechatLogin">
        <view v-if="loading" class="loading-spinner"></view>
        <view class="wechat-icon-img-container">
          <view class="wechat-icon-img-container-item">
            <image
              src="/static/icons/wechat.svg"
              class="wechat-icon-img"
              mode="aspectFit"
              @error="handleWechatIconError"
            />
          </view>
          <view class="wechat-icon-text"> 微信一键登录 </view>
        </view>
      </button>

      <view class="agreement">
        <text>点击登录即表示您同意《用户协议》和《隐私政策》</text>
      </view>
    </view>

    <!-- 底部信息 -->
    <view class="footer"> © 2023 医疗健康平台 | 提供专业医疗服务 </view>
  </view>
</template>

<script>
export default {
  name: "LoginPage",
  data() {
    return {
      loading: false,
      showFallbackIcon: false,
      showWechatFallback: false,
    };
  },
  computed: {
    isLoggedIn() {
      return this.$store.getters["auth/isLoggedIn"];
    },
    needProfilePrompt() {
      return this.$store.getters["auth/needProfilePrompt"];
    },
  },
  onLoad(options) {
    // 如果有重定向参数，保存起来
    if (options.redirect) {
      this.redirectUrl = decodeURIComponent(options.redirect);
    }

    // 恢复登录状态
    this.$store.dispatch("auth/restoreLoginStatus");
  },
  methods: {
    // 微信一键登录
    async handleWechatLogin() {
      if (this.loading) return;

      try {
        this.loading = true;

        const result = await this.$store.dispatch("auth/wechatLogin");

        if (result.success) {
          uni.showToast({
            title: "登录成功",
            icon: "success",
          });

          setTimeout(() => {
            this.navigateAfterLogin();
          }, 1500);
        } else {
          throw new Error(result.error);
        }
      } catch (error) {
        console.error("微信登录失败:", error);
        uni.showToast({
          title: error.message || "微信登录失败",
          icon: "error",
          duration: 2000,
        });
      } finally {
        this.loading = false;
      }
    },

    // 登录后跳转
    navigateAfterLogin() {
      const tabBarPages = [
        "/pages/home/index",
        "/pages/appointment/index",
        "/pages/drugs/index",
        "/pages/profile/index",
      ];

      const target = this.redirectUrl || "/pages/home/index";

      // 登录成功后立即触发位置上传
      this.triggerLocationUpload();

      // 如果需要资料授权，先提示用户授权
      if (this.needProfilePrompt) {
        this.$store.dispatch("auth/setNeedProfilePrompt", true);
        uni.showModal({
          title: "完善资料",
          content: "为更好地展示个人信息，建议获取头像和昵称",
          confirmText: "去授权",
          cancelText: "稍后",
          success: (res) => {
            if (res.confirm) {
              this.requestProfile();
            } else {
              this.gotoTarget(target, tabBarPages);
            }
          },
        });
        return;
      }

      this.gotoTarget(target, tabBarPages);
    },

    gotoTarget(target, tabBarPages) {
      if (tabBarPages.includes(target)) {
        uni.switchTab({ url: target });
      } else {
        uni.redirectTo({ url: target });
      }
    },

    async requestProfile() {
      try {
        const res = await this.$store.dispatch("auth/requestUserProfile");
        if (res && res.success) {
          const tabBarPages = [
            "/pages/home/index",
            "/pages/appointment/index",
            "/pages/drugs/index",
            "/pages/profile/index",
          ];
          const target = this.redirectUrl || "/pages/home/index";
          this.gotoTarget(target, tabBarPages);
        } else {
          console.log("[登录页] 授权失败:", res?.error);
          if (res?.error && !res.error.includes("用户取消")) {
            uni.showToast({
              title: res.error,
              icon: "none",
              duration: 2000,
            });
          }
        }
      } catch (error) {
        console.error("[登录页] requestProfile出错:", error);
        uni.showToast({
          title: "授权失败，请重试",
          icon: "none",
          duration: 2000,
        });
      }
    },

    // 显示用户协议
    showAgreement() {
      uni.showModal({
        title: "用户协议",
        content: "这里是用户协议内容...",
        showCancel: false,
      });
    },

    // 显示隐私政策
    showPrivacy() {
      uni.showModal({
        title: "隐私政策",
        content: "这里是隐私政策内容...",
        showCancel: false,
      });
    },

    // 处理图标加载错误
    handleIconError() {
      console.log("医疗图标加载失败，使用默认图标");
      this.showFallbackIcon = true;
    },

    // 处理微信图标加载错误
    handleWechatIconError() {
      console.log("微信图标加载失败，使用默认图标");
      this.showWechatFallback = true;
    },

    // 触发位置上传
    async triggerLocationUpload() {
      try {
        console.log("登录成功，触发位置上传...");

        const currentLocation = this.$store.getters["location/currentLocation"];

        if (currentLocation && !currentLocation.isDefault) {
          const uploadResult = await this.$store.dispatch(
            "location/uploadLocation",
            {
              deviceType: "wxapp",
              source: "login_upload",
            }
          );
          console.log("登录后位置上传结果:", uploadResult);

          await this.$store.dispatch("location/initRealtimePush");
        } else {
          console.log("没有有效位置，跳过上传");
        }
      } catch (error) {
        console.error("登录后位置上传失败:", error);
      }
    },
  },
};
</script>

<style lang="scss" scoped>
/* 小程序WXSS兼容的样式重置 */

view,
text,
button,
image {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}
.wechat-icon-text-container text {
  display: block;
  font-size: 32rpx;
  color: white;
  padding: 0;
}
.container {
  background-color: #f5f7fa;
  color: #333;
  line-height: 1.6;
  min-height: 100vh;
  display: flex;
  // flex-direction: column;
  padding: 40rpx 20rpx;
  width: 100%;
  justify-content: center;
  align-items: center;
  font-family: "PingFang SC", "Helvetica Neue", Arial, sans-serif;
}

/* 顶部logo和欢迎信息 */
.header {
  text-align: center;
  margin-bottom: 100rpx;
  width: 100%;
  display: flex;
  flex-direction: column;
  align-items: center;
}

.logo {
  display: inline-flex;
  align-items: center;
  justify-content: center;
  width: 160rpx;
  height: 160rpx;
  background: linear-gradient(135deg, #2c7dbe 0%, #50b4c8 100%);
  border-radius: 40rpx;
  color: white;
  margin-bottom: 40rpx;
  box-shadow: 0 8rpx 24rpx rgba(44, 125, 190, 0.2);
}

.medical-icon {
  position: relative;
  display: flex;
  align-items: center;
  justify-content: center;
  width: 100%;
  height: 100%;
}

.icon-image {
  width: 64rpx;
  height: 64rpx;
  filter: brightness(0) invert(1); /* 让图标变为白色 */
}

.fallback-icon {
  font-size: 64rpx;
  color: white;
  display: flex;
  align-items: center;
  justify-content: center;
}

/* 移除了heartbeat动画，保持图标静态显示 */

.title {
  font-size: 48rpx;
  color: #2c7dbe;
  margin-bottom: 30rpx;
  font-weight: 600;
}

.description {
  font-size: 32rpx;
  color: #666;
  max-width: 600rpx;
  margin: 0 auto;
  line-height: 1.6;
}

/* 微信登录按钮 */
.wechat-login {
  width: 100%;
  max-width: 600rpx;
  text-align: center;
  margin: 80rpx auto;
}

.wechat-btn {
  width: 100%;
  max-width: 600rpx;
  margin: 0 auto;
  padding: 32rpx 40rpx;
  background-color: #07c160;
  color: white;
  border: none;
  border-radius: 24rpx;
  font-size: 32rpx;
  font-weight: 500;
  cursor: pointer;
  transition: all 0.3s;
  box-shadow: 0 8rpx 24rpx rgba(7, 193, 96, 0.2);
  position: relative;

  &:hover {
    opacity: 0.9;
    transform: translateY(-4rpx);
    box-shadow: 0 12rpx 32rpx rgba(7, 193, 96, 0.3);
  }

  &:active {
    transform: translateY(0);
  }

  &:disabled {
    opacity: 0.7;
    cursor: not-allowed;
  }

  text:last-child {
    margin-left: 0;
  }
}

.wechat-icon-img {
  // margin-top: 20rpx;
  width: 44rpx;
  height: 44rpx;
  filter: brightness(0) invert(1); /* 让SVG图标变为白色 */
}
.wechat-icon-text {
  width: 200rpx;
}
.wechat-icon-img-container-item {
  width: 20%;
}

.wechat-icon-img-container{
  padding: 0 140rpx;
  display: flex;
  align-items: center;
  justify-content: space-between;
  flex-direction:row;
}
 .loading-spinner {
  width: 40rpx;
  height: 40rpx;
  border: 4rpx solid rgba(255, 255, 255, 0.3);
  border-top-color: white;
  border-radius: 50%;
  animation: spin 0.8s linear infinite;
  margin-right: 20rpx;
}

@keyframes spin {
  to {
    transform: rotate(360deg);
  }
}

/* 协议说明 */
.agreement {
  text-align: center;
  margin-top: 60rpx;
  font-size: 20rpx;
  color: #999;
  width: 100%;
  line-height: 1.4;
  padding: 0 20rpx;
  display: flex;
  flex-wrap: nowrap;
  justify-content: center;
  align-items: center;
}

.link {
  color: #2c7dbe;
  text-decoration: none;
  display: inline;
  white-space: nowrap;
}

/* 底部装饰 */
.footer {
  text-align: center;
  margin-top: 80rpx;
  color: #999;
  font-size: 24rpx;
}

/* 响应式调整 */
@media screen and (max-height: 1200rpx) {
  .header {
    margin-bottom: 60rpx;
  }

  .wechat-login {
    margin: 40rpx 0;
  }
}
</style>